package com.xuanyuanzi.all_learning.web.controller.sys;

import cn.hutool.core.util.IdUtil;
import com.wf.captcha.base.Captcha;
import com.xuanyuanzi.all_learning.application.dto.AuthUserDto;
import com.xuanyuanzi.all_learning.infrastructure.common.aop.JwtTokenAuth;
import com.xuanyuanzi.all_learning.infrastructure.common.enums.LoginCodeEnum;
import com.xuanyuanzi.all_learning.infrastructure.common.utils.RedisUtils;
import com.xuanyuanzi.all_learning.infrastructure.common.utils.RsaUtils;
import com.xuanyuanzi.all_learning.infrastructure.config.bean.LoginProperties;
import com.xuanyuanzi.all_learning.infrastructure.config.bean.SecurityProperties;
import com.xuanyuanzi.all_learning.infrastructure.config.properties.RsaProperties;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author chen.xuan
 * @Description 用户登录认证相关接口
 * @date 2024/10/24 15:28
 */
@RestController("pcAuthApi")
@RequestMapping("/sys/auth")
@JwtTokenAuth
@RequiredArgsConstructor
public class AuthApi {
    private final RedisUtils redisUtils;
    private final LoginProperties loginProperties;
    private final SecurityProperties securityProperties;
    @ApiOperation("登录授权")
    @PostMapping(value = "/login")
    public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception {

        // 密码解密 -> 对应前端（    组件："jsencrypt": "^3.0.0-rc.1",）
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword());
        // 查询验证码
        String code = (String) redisUtils.get(authUser.getUuid());
        // 清除验证码
        redisUtils.del(authUser.getUuid());
        if (StringUtils.isBlank(code)) {
//            throw new BadRequestException("验证码不存在或已过期");
        }
        if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) {
//            throw new BadRequestException("验证码错误");
        }
/*        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(authUser.getUsername(), password);
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 生成令牌与第三方系统获取令牌方式
        // UserDetails userDetails = userDetailsService.loadUserByUsername(userInfo.getUsername());
        // Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        // SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = tokenProvider.createToken(authentication);
        final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal();
        // 返回 token 与 用户信息
        Map<String, Object> authInfo = new HashMap<String, Object>(2) {{
            put("token", properties.getTokenStartWith() + token);
            put("user", jwtUserDto);
        }};
        if (loginProperties.isSingleLogin()) {
            // 踢掉之前已经登录的token
            onlineUserService.kickOutForUsername(authUser.getUsername());
        }
        // 保存在线信息
        onlineUserService.save(jwtUserDto, token, request);*/
        // 返回登录信息
        return ResponseEntity.ok(null);
    }

    @ApiOperation("获取验证码")
    @GetMapping("/code")
    public ResponseEntity<Object> getCode() {
        // 获取运算的结果
        Captcha captcha = loginProperties.getCaptcha();
        String uuid = securityProperties.getCodeKey() + IdUtil.simpleUUID();
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == LoginCodeEnum.ARITHMETIC.ordinal() && captchaValue.contains(".")) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        // 保存
        redisUtils.set(uuid, captchaValue, loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return ResponseEntity.ok(imgResult);
    }
}
